package com.woniuxy.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.woniuxy.entity.User;
import com.woniuxy.mapper.UserMapper;
import com.woniuxy.service.UserService;
import com.woniuxy.util.ConstantPropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public void register(User user) {
        userMapper.insert(user);
    }

    @Override
    public User findByAccountOrEmail(User user) {
        return userMapper.findByAccountOrEmail(user);
    }

    @Override
    public void updateByUserId(User user) {
        userMapper.updateByUserId(user);
    }

    @Override
    public String   updateAvatar(MultipartFile file, Integer userId) throws IOException {
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        //获取上传文件输入流对象
        InputStream is = file.getInputStream();
        //获取上传文件原名称
        String original = file.getOriginalFilename();
        //截取文件后缀名
        String suffix = original.substring(original.indexOf("."));
        //使用uuid随机一个唯一文件名称
        String prefix = UUID.randomUUID().toString().replaceAll("-","");

        //把文件按照日期进行分类存放  比如: /2022/05/20/xxx.jpg
        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        //拼接上传文件存放路径和名称
        String fileName = datePath + "/" + prefix + suffix;


        //调用oss方法实现文件上传
        //第一个参数:表示bucket名称
        //第二个参数:表示上传到oss文件路径和文件名称   a/b/1.jpg
        //第三个参数:上传文件输入流
        ossClient.putObject(bucketName, fileName, is);
        //关闭ossClient
        ossClient.shutdown();
        //把上传到阿里云oss的文件路径返回

        String url = "https://" +bucketName + "." + endPoint +  "/" + fileName;
        //更新数据库表数据
        System.out.println(url);
        userMapper.updateAvatar(url,userId);

        return url;
    }

    @Override
    public void updatePassword(User user) {
        userMapper.updatePassword(user);
    }
}
